package no.ntnu.item.ttm4115.termproject.imagent.gui;


/****************************************************************/
/*                      MessengerWindow	                         */
/*                                                              */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.*;

import no.ntnu.item.ttm4115.termproject.ChatMessage;
import no.ntnu.item.ttm4115.termproject.ClosingChat;
import no.ntnu.item.ttm4115.termproject.InstantMessage;
import no.ntnu.item.ttm4115.termproject.playeragent.gui.MeetingPlaceGUI;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;
/**
 * Summary description for MessengerWindow
 *
 */
@SuppressWarnings("serial")
public class IMWindow extends JPanel
{
	// Variables declaration
	private String receiverName;
	private MeetingPlaceGUI mainFrame;
	private ActorSM asm;
	private ActorAddress receiver;
	private String playerName;
	@SuppressWarnings("unused")
	private JPanel jPanelIM;
	private JScrollPane jScrollPane4;
    private JScrollPane jScrollPane5;
    private JButton sendButton;
    private JButton closeButton;
	private JTextArea IMchatTextArea;
	private JList jListIMInput;
	private DefaultListModel imChatModel;
	private final static String newline = "\n";
	{
		//Set Look & Feel
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	// End of variables declaration
	


	public IMWindow(ActorSM asm, ActorAddress receiver, String playerName, String receiverName, MeetingPlaceGUI mainFrame)
	{
		//super();
		System.out.println("IM window starts");
		this.mainFrame = mainFrame;
		this.mainFrame.getPane().addTab(receiverName, this);
		this.repaint();
        this.mainFrame.repaint();
		this.asm = asm;
		this.receiver = receiver;
        this.playerName = playerName;
        this.receiverName = receiverName;
        
        initComponents();
	}
	
        
	private void initComponents() {
		
		
		
		IMchatTextArea = new JTextArea();
		jScrollPane4 = new JScrollPane();
		jScrollPane5 = new JScrollPane();
		jListIMInput = new JList();
		sendButton = new JButton();
		closeButton = new JButton();
		jPanelIM = new JPanel();
		imChatModel = new DefaultListModel();
		
	
		IMchatTextArea.setText("Type here");
		IMchatTextArea.setText("");
		IMchatTextArea.setColumns(20);
        IMchatTextArea.setRows(5);
		
		//jScrollPane4.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		jScrollPane4.setViewportView(jListIMInput);
		//jScrollPane5.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		jScrollPane5.setViewportView(IMchatTextArea);
		
		
        jListIMInput.setModel(getJListImChatModel());
        jListIMInput.setCellRenderer(new MyCellRenderer());
        
        sendButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_13.png"))); // NOI18N
		sendButton.setText("Send");
		sendButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				sendButton_actionPerformed(e);
			}

		});
		
		closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_05.png"))); // NOI18N
		closeButton.setText("Close");
		closeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e)
			{
				closeButton_actionPerformed(e);
			}

		});
		
		javax.swing.GroupLayout jPanelIMLayout = new javax.swing.GroupLayout(this);
        this.setLayout(jPanelIMLayout);
        jPanelIMLayout.setHorizontalGroup(
            jPanelIMLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanelIMLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanelIMLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
                    .addGroup(jPanelIMLayout.createSequentialGroup()
                        .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanelIMLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(closeButton, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanelIMLayout.setVerticalGroup(
            jPanelIMLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelIMLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 331, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanelIMLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanelIMLayout.createSequentialGroup()
                        .addGap(47, 47, 47)
                        .addComponent(sendButton)
                        .addGap(18, 18, 18)
                        .addComponent(closeButton))
                    .addGroup(jPanelIMLayout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
		
		
	}
		
	public DefaultListModel getJListImChatModel(){
    	return imChatModel;
    }
	
	
	@SuppressWarnings("unused")
	private void addComponent(Container container,Component c,int x,int y,int width,int height)
	{
		c.setBounds(x,y,width,height);
		container.add(c);
	}

		public void systemOkMsg(String message){
			IMchatTextArea.setEditable(true);
			sendButton.setEnabled(true);
			ListItem li = new ListItem(Color.darkGray, message);
			getJListImChatModel().addElement(li);
			this.repaint();
		}
	
		public void systemErrorMsg(String message){
			IMchatTextArea.setEditable(true);
			sendButton.setEnabled(true);
			ListItem li = new ListItem(Color.red, message);
			getJListImChatModel().addElement(li);
			this.repaint();
		}
	
	
		public void receiveMsg(String Message){
    		
        	IMchatTextArea.setEditable(true);
            sendButton.setEnabled(true);
            ListItem li = new ListItem(Color.black, Message);
            getJListImChatModel().addElement(li);                
            this.repaint();
            Date date = new Date();
    		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    		String time = formatter.format(date);
            mainFrame.updateActivityList(time+ ": "+receiverName+" sent you a instant message", "IM");
        }
		
		public void receiveSelfMsg(String Message){
    		
        	IMchatTextArea.setEditable(true);
            sendButton.setEnabled(true);
            ListItem li = new ListItem(Color.black, Message);
            getJListImChatModel().addElement(li);                
            this.repaint();
        }
	
	        
	        public String getPlayerName() {
	                return playerName;
        }

	        private void sendButton_actionPerformed(ActionEvent e)
	    	{
	    		InstantMessage im = new InstantMessage(getPlayerName()+ ": "+IMchatTextArea.getText().toString());
                asm.sendMessage(im, this.receiver);
                sendButton.setEnabled(false);
                IMchatTextArea.setEditable(false);
                receiveSelfMsg(im.message);
                IMchatTextArea.setText("");

	    	}
	        
	        private void closeButton_actionPerformed(ActionEvent e)
	    	{
	        	JDialog.setDefaultLookAndFeelDecorated(true);
	            int response = JOptionPane.showConfirmDialog(null, "Do you really wanna close?"+newline+"Nothing will be saved", "Confirm IM close",
	                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
	            if (response == JOptionPane.NO_OPTION) {
	              
	            } else if (response == JOptionPane.YES_OPTION) {
	            	//asm.sendMessage(new ReleaseThisImAgent(), asm.getContext().getParentAddress());
	            	mainFrame.getPane().removeTabAt(mainFrame.getPane().getSelectedIndex());
	              
	            } else if (response == JOptionPane.CLOSED_OPTION) {
	            	
	            }
	            asm.sendMessage(new ClosingChat(), this.receiver);
	    		
	    	}
	       
	        public void setButton(boolean buttonset){
	        	sendButton.setEnabled(buttonset);
	        }
	        
	        public void setMsgTextField(String insert){
	        	IMchatTextArea.setText(insert);
	        }
	        
	        public void closedChat(){
	            ListItem li = new ListItem(Color.red, "***"+receiverName+" has left the chat. If you wish to continue, please open a new window ");
	            sendButton.setEnabled(false);
	            getJListImChatModel().addElement(li); 
	        }
	        
	        
	        
}

@SuppressWarnings("serial")
class MyCellRenderer extends 
JLabel implements ListCellRenderer {

    public MyCellRenderer () {
    // Don't paint behind the component
    	setBackground(Color.white);
        setOpaque(true);
    }

// Set the attributes of the 
//class and return a reference
public Component getListCellRendererComponent(JList list,
      Object value, // value to display
      int index,    // cell index
      boolean iss,  // is selected
      boolean chf)  // cell has focus?
{
    // Set the text and color 
    //background for rendering
    setText(((ListItem)value).getValue());
    setForeground(((ListItem)value).getColor());

    // Set a border if the list 
    //item is selected 
//          if (iss) {
//              setBorder(
//               BorderFactory.createLineBorder(
//                Color.blue, 2));
//          } else {
//              setBorder(
//               BorderFactory.createLineBorder(
//                list.getForeground(), 2));
//          }
           return this;
      }
   }


			

